<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of reply
 * 自定义回复处理
 * @author xlp
 */
class replyApi {

    public $replyList = null;
    public $replyFile; //缓存文件名
    public $info;
    public $text = ''; //输入内容
    protected $eventConfig = null;

    function __construct(&$info) {
        $this->info = $info;
        //缓存文件名
        $this->replyFile = 'replyCache_u';
        //缓存自定义回复
        $this->replyList = F($this->replyFile);
        if (!$this->replyList) {
            $this->replyList = M('weixin_reply')->field('id,keyword,match_type,reply_type,content,fid')->where(array('status' => 1))->findAll();
            if ($this->replyList) {
                F($this->replyFile, $this->replyList);
            }
        }
        //saveLog('weixin/replyList' , array('info' => $this->replyList));
    }

    //
    function reply($text) {
        $this->text = $text;
        if ($this->replyList) {
            foreach ($this->replyList as $key => $val) {
                if (strExists($val['keyword'], '|')) {//如果是多关键词
                    foreach (explode('|', $val['keyword']) as $value) {
                        if ($value && (strExists($this->text, $value) || strExists($value, $this->text))) {//匹配成功
                            $return = $this->checkReply($key);
                            if ($return) {
                                return $return;
                            }
                        }
                    }
                } elseif (strExists($this->text, $val['keyword']) || strExists($val['keyword'], $this->text)) {
                    $return = $this->checkReply($key);
                    if ($return) {
                        return $return;
                    }
                }
            }
        }
        return null; //此处返回默认无结果回复
    }

    function checkReply($key) {
        //match_type:0全匹配;1:模糊匹配
        if (strExists($this->replyList[$key]['keyword'], '|')) {//如果是多关键词
            foreach (explode('|', $this->replyList[$key]['keyword']) as $value) {
                if ($value && (($this->replyList[$key]['match_type'] == 0 && $value == $this->text) || $this->replyList[$key]['match_type'] == 1 && strExists($this->text, $value))) {//匹配成功
                    return $this->getReply($key);
                }
            }
        } elseif (($this->replyList[$key]['match_type'] == 0 && $this->replyList[$key]['keyword'] == $this->text) || ($this->replyList[$key]['match_type'] == 1 && strExists($this->text, $this->replyList[$key]['keyword']))) {
            return $this->getReply($key);
        }
        return null; //此处返回默认无结果回复
    }

    //匹配成功，根据类型来处理
    function getReply($key) {
        switch ($this->replyList[$key]['reply_type']) {
            case 0://纯文本
                return $this->replyList[$key]['content'];
            case 1://图文
                return $this->replyNews($this->replyList[$key]['fid']);
            case 2://执行动作
                return $this->replyAction($key);
            case 3://互动
                return $this->replyEvent($this->replyList[$key]['fid']);
        }
    }

    //执行动作
    function replyAction($key) {
        $note = '抱歉，动作调用错误-' . $this->replyList[$key]['fid'];
        $isSaveLog = true;
        $message = null;
        $action = null; //回调执行动作
        switch ($this->replyList[$key]['fid']) {
            case 1://帐号绑定
                $note = array(
                    'type' => 'news',
                    'items' => array(
                        array(
                            'title' => '绑定帐号',
                            'description' => '绑定帐号，通过认证以后您可以获得更多使用权限',
                            'picurl' => getImgUrl('upload/pics/banner.jpg'),
                            'url' => U('weixin/user/bind', array('q' => 'set'))
                        )
                ));
                break;
            case 2://社区通知
                $rs = M('notice')->field('nid,source_id,title,content')->where("type=0 AND stime<=" . TIME . " AND etime>=" . TIME . " AND village_id=" . $this->info['village_id'] . " AND status=1")->order('nid desc')->find();
                if ($rs) {
                    if ($rs['source_id']) {
                        $note = $this->replyNews($rs['source_id']);
                    } else {
                        $note = $rs['title'] . "\n" . $rs['content'];
                    }
                } else {
                    $note = "本小区没有最新通知\n<a href=\"" . U('weixin/index/index', array('menu' => 0)) . "\">点击进入结邻公社</a>";
                }
                break;
            case 3://消息中心
                $rs = D('userNotice')->getNoticeList($this->info['uid']);
                $comment = 0; //回复
                $praise = 0; //点赞
                $atme = 0; //@我
                if ($rs) {
                    foreach ($rs as $val) {
                        switch ($val['ntype']) {
                            case 2:
                                $comment = $val['counts'];
                                break;
                            case 3:
                                $praise = $val['counts'];
                                break;
                            case 5:
                                $atme = $val['counts'];
                                break;
                        }
                    }
                }
                $note = "我的消息中心：\n回复:" . $comment . "条\n私信:" . $praise . "条\n@我:" . $atme . "次\n<a href=\"" . U('weixin/user/message') . "\">点击进入查看</a>";
                break;
            case 4://多客服
                $note = array(
                    'type' => 'service'
                );
                //发送客服消息
                $action = 'message';
                $message = array('source_id' => 0, 'title' => '您已进入客服模式', 'content' => '请等待客服应答...');
                break;
            case 5://抢楼
                //是否限制每日抢楼次数
                $config = C('stackopolis');
                if (!$config) {
                    $note = '抱歉，缺少配置数据';
                } else {
                    $count = 0;
                    if ($config['isLimit']) {
                        $where = array('uid' => $this->info['uid'], 'msg_type' => 2, 'content' => $this->text);
                        if ($config['dateLimt']) {
                            $where['create_time[>=]'] = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                            $where['create_time[<=]'] = mktime(59, 59, 59, date('m'), date('d'), date('Y'));
                        }
                        $has = M('access_log')->where($where)->count();
                        $count = $config['isLimit'] - $has;
                        if ($count <= 0) {
                            $note = $config['failMsg'];
                            $isSaveLog = false;
                        }
                    }
                    if (!$config['isLimit'] || ($config['isLimit'] && $count > 0)) {
                        //统计当前是第多少楼
                        $count = M('access_log')->where(array('msg_type' => 2, 'content' => $this->text))->count() + $config['start'];
                        $note = $config['okMsg'];
                    }
                    $note = str_replace(array('{count}', '{isLimit}', '{content}'), array(sprintf("%04d", $count), $config['isLimit'], $this->replyList[$key]['content']), $note);
                }
                break;
            case 6://微信打印照片
                $action = 'printPhoto';
                cacheApi::set($this->info['key'], array('act' => $action), 60 * 10);
                $note = '请输入屏幕上的6位验证码';
                $isSaveLog = false;
                break;
            case 7:
                $note = '您的UID为：' . $this->info['uid'];
                break;
        }
        return array('note' => $note, 'isSaveLog' => $isSaveLog, 'message' => $message, 'action' => $action);
    }

    //回复互动
    function replyEvent($id) {
        T('weixin/event');
        $event = new eventApi($this->info);
        return $event->replyEvent($id);
    }

    //回复图文
    function replyNews($id) {
        $createTime = TIME;
        $rs = M('article')->field('id,type,title,content,description,picurl,url,infotime')->where(array('fid' => 0, 'id' => $id))->order('id desc')->find();
        $items = array();
        $result = array();
        if ($rs) {
            $result[] = $rs;
            if ($rs['type'] == 2) {//多条图文时
                $rsItem = M('article')->field('id,title,content,description,picurl,url,infotime')->where(array('fid' => $rs['id']))->order('id asc')->limit(0, 8)->findAll();
                if ($rsItem) {
                    $result = array_merge_recursive($result, $rsItem);
                }
            }
            $createTime = $rs['infotime'];
        } else {
            return '内容不存在或已删除';
        }
        if ($result) {
            foreach ($result as $val) {
                $items[] = array(
                    'title' => $val['title'],
                    'createTime' => $val['infotime'],
                    'description' => $val['description'],
                    'picurl' => getImgUrl($val['picurl']),
                    'url' => !$val['content'] && $val['url'] ? $val['url'] : U('news/detail', array('id' => $val['id']))
                );
            }
        }
        return array('type' => 'news', 'items' => $items, 'createTime' => $createTime);
    }

}
